import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import moment from 'moment';

import { message, Button, Input, Modal, Row, Col, Table } from 'antd';

import examActions from '../action'

import Room from './view/room';
import Question from './view/question';
import User from './view/user';

export class ExamView extends Component {

  state = {
    roomModal : false,
    userModal : false,
    questionModal : false,
    infoModal : false,
    moment : moment().format('MMMM Do YYYY, h:mm:ss')
  }

  constructor (props) {
    super(props);

    this.timer = null;

    this.roomColumns = [{
      title: '考场名称',
      dataIndex: 'room_name'
    }, {
      title: '考试时间',
      render : (text,record) => {
        return (
          <spa>{record.room_date} {record.room_start_time} ~ {record.room_end_time}</spa>
        )
      }
    },{
      title: '考试状态',
      render : (text,record) => {

        if(moment().format('YYYY-MM-DD') == record['room_date']){
          if(moment().format('HH:mm') < record['room_start_time']){
            return (
              <span>考试时间还没到</span>
            )
          }else if(moment().format('HH:mm') >= record['room_end_time']){
            return (
              <span>考试时间已经结束</span>
            )
          }else{
            var now = moment();
            var end = moment(record['room_end_time'],'HH:mm');
            var timelimit = end.diff(now,'minutes');
            return (
              <span>考试中,剩余<b style={{'color':'green'}}>{timelimit}</b>分</span>
            )
          }
        }else{
          if(moment() < moment(record['room_date'])){
            return (
              <span>本场考试日期还没到</span>
            )
          }
          if(moment() > moment(record['room_date'])){
            return (
              <span>本场考试已经结束</span>
            )
          }
        }
      }
    }];

  }

  componentDidMount () {
    this.getExamDetail(parseInt(this.props.params.$loki));
  }

  /**
   * 开始考试
   */
  handleStart (address) {
    const { examActions } = this.props;
    const self = this;

    Server.start(function () {

      examActions.postEditExam({
        $loki : parseInt(self.props.params.$loki),
        status : 'exam'
      }).then(data=>{
        self.setState({
          infoModal : true
        });

        clearInterval(self.timer);
        self.timer = setInterval(()=>{
          self.setState({
            moment : moment().format('MMMM Do YYYY, h:mm:ss')
          })
        },30000);
      });

    });

  }

  /**
   * 结束考试
   */
  handleStop () {
    const { examActions } = this.props;
    const self = this;

    Server.stop(function () {

      clearInterval(self.timer);
      examActions.postEditExam({
        $loki : parseInt(self.props.params.$loki),
        status : 'end'
      }).then(()=>{
        self.setState({
          infoModal : false
        })
      });

    });
  }

  /**
   * 查看成绩
   */
  handleView () {
    this.props.router.push({
      pathname: '/score/'+this.props.params.$loki
    });
  }

  /**
   * 预览试卷
   */
  handleViewBrowser(){
    const {exam} = this.props;
    const examdetail = exam.get('examdetail') && exam.get('examdetail').toJS();
    const address = 'http://'+ip.address()+':8888/check_exam/'+examdetail.exam_id+'.html';

    Server.start(function () {
      setTimeout(function () {
        openBrowser(address);
      },1000)
    });
  }

  /**
   * 导出
   */
  handleExport(){
    const {exam,examActions} = this.props;
    const examdetail = exam.get('examdetail') && exam.get('examdetail').toJS();
    examActions.getUserList({
      path : examdetail.exam_user_path
    }).then(data=>{

      var arr = [], obj ={};
      data.info.forEach(item=>{
        obj = {
          '姓名' : item.user_name,
          '身份证号' : item.user_idcard,
          '地区' : item.user_area,
          '考场' : item.room_name,
          '考试时间' : item.room_time
        };
        arr.push(obj);
      });

      saveXls(arr,examdetail.exam_name+'_考试信息');

    })
  }

  /**
   * 获取考试详情
   * @param $loki
   */
  getExamDetail ($loki) {
    const { examActions } = this.props;

    examActions.getRoomList({
      exam_id : $loki
    });

    examActions.getExamDetail({
      $loki
    }).then(data=>{

      if(data && data.info){
        if(data.info.status == 'setting'){
          this.props.router.push({
            pathname: '/examlist'
          });
        }
      }else{
        message.error('没有找到该考试');
      }
    });
  }

  render() {

    const {exam} = this.props;
    const dateFormat = 'YYYY-MM-DD';
    let examdetail = exam.get('examdetail');
    let roomlist = exam.get('roomlist');

    if(!examdetail || !roomlist){
      return (
        <div></div>
      )
    }
    examdetail = examdetail.toJS();
    roomlist = roomlist.toArray();

    const address = 'http://'+ip.address()+':8888';
    const question_count = parseInt(examdetail.exam_single.num) + parseInt(examdetail.exam_multiple.num) + parseInt(examdetail.exam_tfng.num);

    const statusObj = {
      finish : '配置完成',
      setting : '配置中',
      end : '考试完成',
      exam : '考试中'
    };

    return (
      <div className="ant-content">
        <h2>考试链接:</h2>
        <Input defaultValue={address} />

        <h2 style={{marginTop:'20px'}}>考试名称:{examdetail.exam_name}</h2>

        <Row>
          <Col span={16}>
            <ul className="ant-exam-info">
              <li>
                开始时间:{moment(examdetail.exam_start_date,dateFormat).format('YYYY-MM-DD')} /
                结束时间:{moment(examdetail.exam_end_date,dateFormat).format('YYYY-MM-DD')}
              </li>
              <li>出题类型:{examdetail.exam_qetype === '0' ? '题目相同' : '题目不同'}</li>
              <li>
                考题信息:
                <ul>
                  <li>单选题:{examdetail.exam_single.num}个*{examdetail.exam_single.score}分</li>
                  <li>多选题:{examdetail.exam_multiple.num}个*{examdetail.exam_multiple.score}分</li>
                  <li>判断题:{examdetail.exam_tfng.num}个*{examdetail.exam_tfng.score}分</li>
                </ul>
              </li>
              <li>
                考试安排:
                <ul>
                  <li>考场:{examdetail.room_count}个 <a href="javascript:;" onClick={()=>{ this.setState({roomModal:true}) }}>查看</a></li>
                  <li>试题:{question_count}个 {examdetail.exam_qetype === '0' && <a href="javascript:;" onClick={()=>{ this.setState({questionModal:true}) }}>查看</a>}</li>
                  <li>学员:{examdetail.user_count}个 <a href="javascript:;" onClick={()=>{ this.setState({userModal:true}) }}>查看</a></li>
                  <li>考试状态:{statusObj[examdetail.status]} <a href="javascript:;" onClick={this.handleViewBrowser.bind(this)}>预览试卷</a></li>
                </ul>
              </li>
            </ul>

            <Button type="primary" style={{marginRight:'10px'}} onClick={this.handleExport.bind(this)}>导出学员信息</Button>
            {
              (examdetail.status == 'finish' || examdetail.status == 'end') && <Button type="primary" style={{marginRight:'10px'}} onClick={() => this.handleStart()}>开始考试</Button>
            }
            {
              examdetail.status == 'end' && <Button type="primary" style={{marginRight:'10px'}} onClick={() => this.handleView()}>查看成绩</Button>
            }
            {
              examdetail.status == 'exam' && <Button type="primary" style={{marginRight:'10px'}} onClick={() => this.handleStop()}>考试中,停止考试</Button>
            }
            
          </Col>
        </Row>


        <Modal title="考场列表" visible={this.state.roomModal} footer={null} onCancel={()=>{ this.setState({roomModal:false})}} width={900}>
          <Room $loki={this.props.params.$loki} {...this.props}/>
        </Modal>

        <Modal title="试题列表" visible={this.state.questionModal} footer={null} onCancel={()=>{ this.setState({questionModal:false})}} width={900}>
          <Question $loki={this.props.params.$loki} {...this.props}/>
        </Modal>

        <Modal title="学员列表" visible={this.state.userModal} footer={null} onCancel={()=>{ this.setState({userModal:false})}} width={900}>
          <User $loki={this.props.params.$loki} {...this.props}/>
        </Modal>

        <Modal
          title="考试进行中,不要关闭软件!"
          closable={false}
          visible={this.state.infoModal}
          onOk={this.handleStop.bind(this)}
          onCancel={()=>{ clipboard.set(address, 'text') }}
          okText="停止本场考试"
          cancelText="复制考试链接"
        >
          <div style={{'padding':'10px 0px'}}>
            <p style={{'fontSize':'14px','lineHeight':'24px','color':'red'}}>考试进行中,请不要关闭软件,否则考试无法进行!</p>
            <p style={{'fontSize':'14px','lineHeight':'24px','paddingBottom':'10px'}}>考试链接:{address}</p>
            <Table
              bordered
              moment = {this.state.moment}
              columns={this.roomColumns}
              dataSource={roomlist}
              pagination={false}
            />
          </div>
        </Modal>


      </div>
    )
  }

}

export default connect((state)=>{
  return  {
    exam : state.get('exam')
  }
},dispatch => {
  return {
    examActions : bindActionCreators(examActions, dispatch)
  }
})(ExamView);
